﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using University.Workshop.Model;
using University.Workshop.Business;
using University.Workshop.DataAccess;
using System.Net;
using System.Threading;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Globalization;
using University.Workshop.DataAccess.LanguagePack.ClientLanguagePack;
namespace University.Workshop.ClientApp
{
    /// <summary>
    /// Interaction logic for windowStart.xaml
    /// </summary>
    public partial class windowStart : Window
    {
        private string LanguageSelected;
        private string YouDontHaveMoneySufficientToEnterToThisTable;
        private string YouAreInALevelGreaterTheTableDontAccept;
        private string YouCannotJoinToThisTable;
        private string YouHaveToSelectAnExistTable;
        private string LabelMessageRequestSuccesulySent;
        private string LabelMessageYouAreFriends;
        private string LabelMessageUserAccept;
        private string LabelMessageSelectAUserName;
        private string LabelMessageAnErrorOcurred;
        private string FullTable;
        private string LabelMessageConnected;
        private string LabelMessageDisconnected;
        private string LabelMessageLevel;
        private string ListBoxMessageRefresh;


        int indexListBoxContacts;
        Client client=new Client();
        Client contactClient = new Client();
        Client Player = new Client();
        Client Banned = new Client();
        Client Level=new Client();
        DispatcherTimer timer = new DispatcherTimer();
        string lastButton;
        RelationshipsManager relations = new RelationshipsManager();
        ContactsManager contacts = new ContactsManager();
        User user=new User();
        Thread game=null;
        Thread Ban = null;
        PokerTable table = null;
        PokerGame.PokerTable.CreateTableOption CreateAndPlay = null;
        //UserBuyChipsCard Buy = null;
        PokerGame.Transaction.PokerGameSendCredit TransactionManager = null;
        MiniGame games = null;
        UsersOnTable userTable = null;
        private Collection<Workshop.Model.TableProperties> TablesGame = new Collection<TableProperties>();
        LiderBoard lider = null;
        LevelRules levelRules = null;
        public windowStart()
        { }
        public windowStart(User userReceived)
        {
            InitializeComponent();
            //TODO Title = user.Name;
        //    client.receive();
         //   client.Send("Regular");
          //  client.receive();
            lastButton = " ";
            indexListBoxContacts = -1;
            user = userReceived;
            labelHello.Content = labelHello.Content + user.Name;
            timer.Tick += new EventHandler(ChargeContacts); //refer to msdn: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer.aspx
            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Start();
            game = new Thread(receiveGames);
            game.Start();
            //Ban = new Thread(WaitBan);
            //Ban.Start();
        }

        public windowStart(User userReceived, string languageSelected)
        {
            InitializeComponent();
            //TODO Title = user.Name;
            //    client.receive();
            //   client.Send("Regular");
            //  client.receive();
            lastButton = " ";
            indexListBoxContacts = -1;
            user = userReceived;
            
            timer.Tick += new EventHandler(ChargeContacts);
            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Start();
            game = new Thread(receiveGames);
            game.Start();
            Ban = new Thread(WaitBan);
            Ban.Start();

            this.LanguageSelected = languageSelected;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.LanguageSelected);
            ApplyLanguage();
            labelHello.Content = labelHello.Content + " " + user.Name;
        }

        private void ApplyLanguage()
        {
            this.buttonProfile.Content = ClientLanguagePack.WindowsStartButtonViewProfile;
            this.button1.Content = ClientLanguagePack.WindowsStartButtonBuyChips;
            this.buttonTransfer.Content = ClientLanguagePack.WindowsStartButtonTransferChips;
            this.buttonGames.Content = ClientLanguagePack.WindowsStartButtonMiniGames;
            this.button2.Content = ClientLanguagePack.WindowsStartButtonGalleryDeck;
            this.Liders.Content = ClientLanguagePack.WindowsStartButtonLiderBoard;
            this.button4.Content = ClientLanguagePack.WindowsStartButtonViewLevelRules;
            this.button3.Content = ClientLanguagePack.WindowsStartButtonWatchTable;
            this.joinButton.Content = ClientLanguagePack.WindowsStartButtonJoin;
            this.buttonAccept.Content = ClientLanguagePack.WindowsStartButtonAcceptRequest;
            this.buttonMake.Content = ClientLanguagePack.WindowsStartButtonSendRequest;
            this.buttonWatchProfile.Content = ClientLanguagePack.WindowsStartButtonWatchProfile;
            this.createButton.Content = ClientLanguagePack.WindowsStartButtonCreate;
            
            this.label1.Content = ClientLanguagePack.WindowsStartLabelDisponibleTables;
            this.label2.Content = ClientLanguagePack.WindowsStartLabelPeople;
            this.labelHello.Content = ClientLanguagePack.WindowsStartLabelWelcome;

            this.YouDontHaveMoneySufficientToEnterToThisTable = ClientLanguagePack.WindowsStartMessageYouDontHaveMoneySufficientToEnterToThisTable;
            this.YouAreInALevelGreaterTheTableDontAccept = ClientLanguagePack.WindowsStartMessageYouAreInALevelGreaterTheTableDontAccept;
            this.YouCannotJoinToThisTable = ClientLanguagePack.WindowsStartMessageYouCannotJoinToThisTable;
            this.YouHaveToSelectAnExistTable = ClientLanguagePack.WindowsStartMessageYouHaveToSelectAnExistTable;
            this.LabelMessageRequestSuccesulySent = ClientLanguagePack.WindowsStartLabelMessageRequestSuccesulySent;
            this.LabelMessageYouAreFriends = ClientLanguagePack.WindowsStartLabelMessageYouAreFriends;
            this.LabelMessageUserAccept = ClientLanguagePack.WindowsStartLabelMessageUserAccept;
            this.LabelMessageSelectAUserName = ClientLanguagePack.WindowsStartLabelMessageSelectAUserName;
            this.LabelMessageAnErrorOcurred = ClientLanguagePack.WindowsStartLabelMessageAnErrorOcurred;
            this.FullTable = ClientLanguagePack.WindowsStartMessageFullTable;
            this.LabelMessageConnected = ClientLanguagePack.WindowsStartLabelMessageConnected;
            this.LabelMessageDisconnected = ClientLanguagePack.WindowsStartLabelMessageDisconnected;
            this.LabelMessageLevel = ClientLanguagePack.WindowsStartLabelMessageLevel;
            this.ListBoxMessageRefresh = ClientLanguagePack.WindowsStartListBoxMessageRefresh;

            this.groupBox_ChipsProperties.Header = ClientLanguagePack.WindowsStartGroupBoxChipsProperties;
            this.groupBox_Friends.Header = ClientLanguagePack.WindowsStartGroupBoxFriends;
            this.groupBox_GamesTables.Header = ClientLanguagePack.WindowsStartGroupBoxGamesTables;
        }

        public void getGames()
        {                        
            Player.Send("26");
            int number=Convert.ToInt32(Player.Receive());
            Player.Send("Start");
            
            string []newGame;            
            for (int iterator = 0; iterator < number; iterator++)
            {
                newGame = Player.Receive().Split(' ');                
                Workshop.Model.TableProperties Table = new TableProperties { IPAddress = newGame[0], UserCreator = newGame[1], TotalPlayers = newGame[2], RuleLevel = newGame[3], MaximumBet = newGame[4], MinimumBet = newGame[5], TableName = newGame[6].Replace("#"," ") };
                TablesGame.Add(Table);

                Player.Send("Next");
                
            }
            Tables.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
     new Action(delegate()
            {
                dataGrid_ListGames.ItemsSource = TablesGame;
            }));
              
        }
        
        public void receiveGames()
        {
            Player.Send("23");
            Player.Receive();
            getGames();
            while (true)
            {
                string[] newGame = Player.Receive().Split(' ');
                Workshop.Model.TableProperties Table = null;
                
                if (newGame.Length >= 7)
                {
                    Table = new TableProperties { IPAddress = newGame[1], UserCreator = newGame[2], TotalPlayers = newGame[3], RuleLevel = newGame[4], MaximumBet = newGame[5], MinimumBet = newGame[6], TableName = newGame[7].Replace("#"," ") };
                }               

                if (newGame[0] == "00")
                {
              //      Tables.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              //new Action(delegate() { Tables.Items.Add(newGame[1]); }));
              //      Names.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              //new Action(delegate() { Names.Items.Add(newGame[2]); }));
                    
                    TablesGame.Add(Table);
                    dataGrid_ListGames.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              new Action(delegate() { dataGrid_ListGames.ItemsSource = null; }));
                    dataGrid_ListGames.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              new Action(delegate() { dataGrid_ListGames.ItemsSource = TablesGame; }));
                    
                }
                if (newGame[0] == "01")
                {
               //     Tables.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
               //new Action(delegate() { Tables.Items.Remove(newGame[1]); }));

               //     Names.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
               //new Action(delegate() { Names.Items.Remove(newGame[2]); }));
                                        
                    for (int Pointer = 0; Pointer < TablesGame.Count; Pointer++)
                    {
                        if (TablesGame[Pointer].UserCreator == Table.UserCreator)
                        {
                            TablesGame.Remove(TablesGame[Pointer]);
                        }
                    }
                    dataGrid_ListGames.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              new Action(delegate() { dataGrid_ListGames.ItemsSource = null; }));
                    dataGrid_ListGames.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              new Action(delegate() { dataGrid_ListGames.ItemsSource = TablesGame; }));
                    
                }
            }
        }
        private void ChargeContacts(object sender,EventArgs e)
        {
            relations = new RelationshipsManager();
            contacts = new ContactsManager();
            contacts.SetAll(contactClient.GetUsersContacts(user.Name));
            contacts.Separate(user.Name);
            relations.SetAll(contactClient.GetAllUsers);
            Copy(user.Name);
            indexListBoxContacts = listBox1.SelectedIndex;
            listBox1.Items.Clear();
            
            switch (lastButton)
            { 
                case "AllPeople":
                    foreach (User userOnly in relations.PeopleNotKnow)
                    {
                        if (userOnly.Name != user.Name)
                            listBox1.Items.Add(userOnly.Name);
                    }
                    break;
                case "Friends":
                    foreach (User userOnly in relations.Friends)
                    {
                        listBox1.Items.Add(userOnly.Name);
                    }
                    break;
                case "PendingSend":
                    foreach (User userOnly in relations.PendingSend)
                        listBox1.Items.Add(userOnly.Name);
                    break;
                case "PendingReceived":
                    foreach (User userOnly in relations.PendingReceived)
                        listBox1.Items.Add(userOnly.Name);
                    break;
            }
            if (indexListBoxContacts != -1 && indexListBoxContacts<=listBox1.Items.Count)
            {
                listBox1.SelectedIndex = indexListBoxContacts;
            }
            int countSend = relations.PendingSend.Count;
            int countReceived = relations.PendingReceived.Count;
            if (countSend == 0)
            {
                labelSend.Visibility = Visibility.Hidden;
                border1.Visibility = Visibility.Hidden;
            }
            else
            {
                border1.Visibility = Visibility.Visible;
                labelSend.Visibility = Visibility.Visible;
                labelSend.Content = countSend;
            }
            if (countReceived == 0)
            {

                labelReceived.Visibility = Visibility.Hidden;
                border2.Visibility = Visibility.Hidden;
            }
            else
            {
                border2.Visibility = Visibility.Visible;
                labelReceived.Visibility = Visibility.Visible;
                labelReceived.Content = countReceived;
            }
        }
        private User lookingFor(string userName)
        {
            foreach (User userOnly in relations.All)
            {
                if (userOnly.Name == userName)
                    return userOnly;
            }
            return null;
        }
        private void Copy(string userName)
        {
            foreach (UserContacts userContact in contacts.Friends)
            {
                User userOnly;
                if (userContact.UserName == userName)
                    userOnly = lookingFor(userContact.UserRequest);
                else
                    userOnly = lookingFor(userContact.UserName);
                if (userOnly != null)
                {
                    relations.Friends.Add(userOnly);
                }
            }
            foreach (UserContacts userContact in contacts.PendingSend)
            {
                User userOnly = lookingFor(userContact.UserRequest);
                if (userOnly != null)
                {
                    relations.PendingSend.Add(userOnly);
                }
            }
            foreach (UserContacts userContact in contacts.PendingReceive)
            {
                User user = lookingFor(userContact.UserName);
                if (user != null)
                {
                    relations.PendingReceived.Add(user);
                }
            }
            relations.AddPeopleNotKnow(relations.All);
            
        }

        private void buttonMake_Click(object sender, RoutedEventArgs e)
        {
            labelMessage.Content = " ";
            if (listBox1.SelectedIndex != -1)
            {
                string userRequest = listBox1.SelectedItem.ToString();
                if(client.SendRequest(user.Name, userRequest))
                {
                    labelMessage.Content = this.LabelMessageRequestSuccesulySent;
                    relations.PendingSend.Add(lookingFor(userRequest));
                    relations.PeopleNotKnow.Remove(lookingFor(userRequest));
                    listBox1.Items.Clear();
                    foreach (User userOnly in relations.PeopleNotKnow)
                    {
                        if(userOnly.Name != user.Name)
                            listBox1.Items.Add(userOnly.Name);
                    }
                }
                else
                    labelMessage.Content = this.LabelMessageYouAreFriends;
            }
        }
        private void changePicture(Image image, string path)
        {

            Uri uri = new Uri(path, UriKind.Relative);

            ImageSource imgSource = new BitmapImage(uri);

            image.Source = imgSource;
        }
        private void showProfile()
        {
            if (listBox1.SelectedIndex != -1 && listBox1.SelectedValue != null)
            {
                string username = listBox1.SelectedItem.ToString();
                User userOnly = lookingFor(username);
                Profile profile = new Profile(this.LanguageSelected);
                profile.labelUser.Content = userOnly.Name;
                profile.labelMail.Content = userOnly.Email;
                profile.labelChips.Content = userOnly.Chips;
                string path="LevelImages/Level"+userOnly.UserLevel+".jpg";
                changePicture(profile.imageLevel,path);
                profile.labelLevelString.Content = userOnly.GetLevel + this.LabelMessageLevel + userOnly.UserLevel + ")";
                profile.labelTimeWon.Content = Convert.ToString(userOnly.TimeWon);
                profile.labelLevel.Content = userOnly.UserLevel;
                if (userOnly.Status == 1)
                    profile.labelStatus.Content = this.LabelMessageConnected;
                else
                    profile.labelStatus.Content = this.LabelMessageDisconnected;
                
                profile.Show();
            }
            else
            {
                labelMessage.Content = this.LabelMessageSelectAUserName;
            }
        }
        private void buttonWatchProfile_Click(object sender, RoutedEventArgs e)
        {
            labelMessage.Content = " ";
            showProfile();
        }

        private void buttonAccept_Click(object sender, RoutedEventArgs e)
        {
            if (listBox1.SelectedIndex != -1)
            {
                string userRequest = listBox1.SelectedItem.ToString();
                if (client.ChangeStatus(userRequest, user.Name, "Friends"))
                {
                    labelMessage.Content = this.LabelMessageUserAccept;
                    relations.Friends.Add(lookingFor(userRequest));
                    relations.PendingReceived.Remove(lookingFor(userRequest));
                    listBox1.Items.Clear();
                    foreach (User userOnly in relations.PendingReceived)
                        listBox1.Items.Add(userOnly.Name);
                }
                else
                    labelMessage.Content = this.LabelMessageAnErrorOcurred;
            }
        }

        private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Collection<LevelDatabase>levels= client.GetAllLevels;
            PokerTable table = new PokerTable(2999, user,relations,levels);
            table.Show();
        }

        

        private void ListBoxItem_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
        {
            try
            {
                Collection<LevelDatabase> levels = client.GetAllLevels;
                PokerTable table = new PokerTable(2999, user,relations,levels);
                table.Show();
            }
            catch(Exception)
            {
                MessageBox.Show(this.FullTable);
            }
             
             
        }

        private void buttonFriends_Click(object sender, RoutedEventArgs e)
        {
            lastButton = "Friends";
            buttonAccept.IsEnabled = false;
            labelMessage.Content = " ";
            listBox1.Items.Clear();
            buttonMake.IsEnabled = false;

            foreach (User userOnly in relations.Friends)
                listBox1.Items.Add(userOnly.Name);
        }

        private void buttonAllPeople_Click_1(object sender, RoutedEventArgs e)
        {
            lastButton = "AllPeople";
            buttonAccept.IsEnabled = false;
            labelMessage.Content = " ";
            listBox1.Items.Clear();
            buttonMake.IsEnabled = true;
            foreach (User userOnly in relations.PeopleNotKnow)
            {
                if (userOnly.Name != user.Name)
                    listBox1.Items.Add(userOnly.Name);
            }
        }

        private void buttonPendingSend_Click_1(object sender, RoutedEventArgs e)
        {
            lastButton = "PendingSend";
            buttonAccept.IsEnabled = false;
            labelMessage.Content = " ";
            listBox1.Items.Clear();
            buttonMake.IsEnabled = false;

            foreach (User userOnly in relations.PendingSend)
                listBox1.Items.Add(userOnly.Name);
        }

        private void buttonPendingReceived_Click_1(object sender, RoutedEventArgs e)
        {
            lastButton = "PendingReceived";
            buttonAccept.IsEnabled = true;
            labelMessage.Content = " ";
            listBox1.Items.Clear();
            buttonMake.IsEnabled = false;

            foreach (User userOnly in relations.PendingReceived)
                listBox1.Items.Add(userOnly.Name);
        }

        

        private void ListBoxItem_Selected(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MyProfile Edit = new MyProfile(user);
            Edit.Show();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            
         }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Buy = new UserBuyChipsCard(user);
            //Buy.ShowDialog();
            client.Send("91 " + user.Name);
            string result = client.Receive();
            user.Loan = result;
            if ((user.Loan == "no" && user.Chips < 500) || (user.Loan != "no" && user.Chips >= Convert.ToInt16( result) ))
            {
                Loan loan = new Loan(user);
                loan.ShowDialog();
            }
            else
            {               
                if (user.Loan == "no" && user.Chips >= 500) 
                       MessageBox.Show("you have 500 chips or more you can not access loan");
                if(user.Loan != "no" && user.Chips < Convert.ToInt16(result))
                       MessageBox.Show("you have a debt and do not have enough money to pay");    
            }            
        }

        private void buttonTransfer_Click(object sender, RoutedEventArgs e)
        {
            TransactionManager = new PokerGame.Transaction.PokerGameSendCredit(this.LanguageSelected, this.user, this.user.Chips);
            TransactionManager.ShowDialog();
        }

        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Clear();
            listBox1.Items.Add(this.ListBoxMessageRefresh);
        }

        private void ButtonLogout_Click(object sender, RoutedEventArgs e)
        {
            /*client.Send("43 " + user.Name.ToLower() + " 0");
            client.Receive();
            Player.Send("25");
            if (game != null)
            {
                if (game.IsAlive)
                {
                    game.IsBackground = true;
                    game.Abort();
                }
            }
            if (Ban != null)
            {
                if (Ban.IsAlive)
                {
                    Ban.IsBackground = true;
                    Ban.Abort();
                }
            }*/
            this.Close();
        }

        private void buttonGames_Click(object sender, RoutedEventArgs e)
        {
            games = new MiniGame(user,this.LanguageSelected);
            games.ShowDialog();
        }

        private void Tables_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void joinButton_Click(object sender, RoutedEventArgs e)
        {
            //asignar deck al join
            //TableManager.Instance.Tables[0].SetDeckOfUser(1);

            try
            {
                TableProperties Auxiliar = (TableProperties)this.dataGrid_ListGames.SelectedItem;
                long MinimusBet = Convert.ToInt64(Auxiliar.MinimumBet);
                long MaximunBet = Convert.ToInt64(Auxiliar.MaximumBet);

                if (user.Chips < MaximunBet)
                {                    
                    MessageBox.Show(this.YouDontHaveMoneySufficientToEnterToThisTable, ":-O");                    
                }
                else
                {
                    int Rule = user.GetUserLevelFromOther(Auxiliar.RuleLevel);
                    //If rule is -1, in the table dont exist rules for play
                    //But if is not -1, the level of user need to be less o equeal
                    if (Rule == -1 || user.UserLevel <= Rule)
                    {
                        TableProperties AuxiliarTable = (TableProperties)this.dataGrid_ListGames.SelectedItem;

                        Collection<LevelDatabase> levels = Level.GetAllLevels;
                        table = new PokerTable(2999, user, textBox1.Text, relations, levels, AuxiliarTable, this.LanguageSelected);
                        table.ShowDialog();

                        Player.Send("14 " + user.Name + " " + user.Chips + " " + user.UserLevel + " " + user.TimeWon);
                    }
                    else
                    {
                        MessageBox.Show(this.YouAreInALevelGreaterTheTableDontAccept, ":-O");                        
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(this.YouCannotJoinToThisTable, ":-\\");
            }
        }
        
        private void createButton_Click(object sender, RoutedEventArgs e)
        {            
            //CreateAndPlay = new PokerGame.PokerTable.CreateTableOption(user, "", this.Tables, this.relations);
            CreateAndPlay = new PokerGame.PokerTable.CreateTableOption(user, this.LanguageSelected, this.dataGrid_ListGames, this.relations);
            CreateAndPlay.ShowDialog();            
            #region OldVersion
            //bool found = false;
            //string ip=LocalIPAddress();
            //foreach (string Item in Tables.Items)
            //{
            //    if (Item.ToString() == ip)
            //        found = true;
            //}
            //if (!found)
            //{
            //    Player.Send("22 " + ip + " " + user.Name);
            //    PokerTable table = new PokerTable(2999, user, relations);

            //    table.ShowDialog();
            //    Player.Send("14 "+user.Name+" "+user.Chips);
            //    Player.Send("24");
            //}
            //else
            //    MessageBox.Show("There is already a table for this IP");
            #endregion
        }


        public string LocalIPAddress()
        {
            string strHostName = Dns.GetHostName();
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                return (ipaddress.ToString());
            }
            return null;
        }

        private void Tables_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (this.Tables.SelectedItem != null)
            {
                this.textBox1.Text = "";
                this.textBox1.Text = this.Tables.SelectedItem.ToString();
            }
        }

        private void Names_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            
            client.Send("43 " + user.Name + " 0");
            client.Receive();
            Player.Send("25");
            if (game != null)
            {
                if (game.IsAlive)
                {
                    game.IsBackground = true;
                    game.Abort();
                }
            }
            if (Ban != null)
            {
                if (Ban.IsAlive)
                {
                    Ban.IsBackground = true;
                    Ban.Abort();
                }
            }
        }
        public void WaitBan()
        {
            Banned.Send("70 " + user.Name);
            string message=Banned.Receive();
            /*if (games != null)
            {

                games.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(delegate()
                {

                    if (games.IsLoaded)
                        games.Close();

                }));
            }
            if (table != null)
            {

                table.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(delegate()
                  {

                      if (table.IsLoaded)
                          table.Close();

                  }));
            }
            if (CreateAndPlay != null)
            {
                  CreateAndPlay.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(delegate()
                  {

                      if (CreateAndPlay.IsLoaded)
                          CreateAndPlay.Close();

                  }));

            
            }
            if (games != null)
            {
                games.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (games.IsLoaded)
                    {
                        games.Ban();
                    }
                }));


            }
            if (Buy != null)
            {
                Buy.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (Buy.IsLoaded)
                    {
                        Buy.Close();
                    }
                }));


            }
            if (TransactionManager != null)
            {
                TransactionManager.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (TransactionManager.IsLoaded)
                    {
                        TransactionManager.Close();
                    }
                }));

            }
            if (userTable != null)
            {
                userTable.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (userTable.IsLoaded)
                    {
                        userTable.Close();
                    }
                }));

            }
            if (lider != null)
            {
                lider.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (lider.IsLoaded)
                    {
                        lider.Close();
                    }
                }));

            }
            if (levelRules != null)
            {
                levelRules.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {

                    if (levelRules.IsLoaded)
                    {
                        levelRules.Close();
                    }
                }));

            }*/
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
              new Action(delegate()
            {
                
                this.Close();
                MessageBox.Show(message);
            
            }));

   
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            user.ResetDeck();
            client.Send("98 " + user.Name);
            string result = client.Receive();
             
            string[] words = result.Split(' ');
            if (words[0]!="no")
            {
                for (int i = 0; i < words.Length; i++)
                {
                    user.Decks.Add(Convert.ToInt32(words[i]));
                }    
            }
            //user.DeckUserPresent = 0;
            //Galery galery = new Galery(user);
            Galery galery = new Galery(user,this.LanguageSelected);
            galery.Show();
        }

        private void Liders_Click(object sender, RoutedEventArgs e)
        {
            lider = new LiderBoard(user);
            lider.ShowDialog();
        }
        private Collection<User> ReceiveClients()
        {
            if (dataGrid_ListGames.SelectedIndex != -1)
            {
                TableProperties table = (TableProperties)(dataGrid_ListGames.SelectedItem);
                Client clientTables = new Client(2999, table.IPAddress);
                clientTables.Send("02");
                string message = clientTables.Receive();
                string[] users;
                clientTables.Send("28");
                int number = Convert.ToInt32(clientTables.Receive());
                Collection<User> usersOfTable = new Collection<User>();
                    if (number > 0)
                    {

                        for (int ID = 0; ID < number; ID++)
                        {
                            usersOfTable.Add(new User());
                            string user;
                            user = clientTables.ReceiveUser();
                            users = user.Split(' ');
                            usersOfTable[ID].Name = users[0];
                            usersOfTable[ID].Chips = Convert.ToInt64(users[1]);
                            usersOfTable[ID].UserLevel = Convert.ToInt32(users[2]);
                            usersOfTable[ID].TimeWon = Convert.ToInt32(users[3]);
                        }
                    }
                return usersOfTable;
            }
            return null;
        }
        private void buttonWatchTables_Click(object sender, RoutedEventArgs e)
        {
            Collection<User> users = ReceiveClients();
            if (users != null)
            {
                userTable = new UsersOnTable(users,this.LanguageSelected);
                userTable.ShowDialog();
            }
            else
            {
                MessageBox.Show(this.YouHaveToSelectAnExistTable, ":-O");
            }
            
        }

        private void dataGrid_ListGames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                TableProperties Auxiliar = (TableProperties)this.dataGrid_ListGames.SelectedItem;
                this.textBox1.Text = Auxiliar.IPAddress;
            }
            catch (NullReferenceException)
            {
                this.textBox1.Text = "";
            }            
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
           levelRules = new LevelRules(this.LanguageSelected);
            levelRules.ShowDialog();
        }

        private void buttonProfile_Click(object sender, RoutedEventArgs e)
        {
            Profile profile = new Profile(this.LanguageSelected);
            profile.labelUser.Content = user.Name;
            profile.labelLevel.Content = user.UserLevel;
            profile.labelMail.Content = user.Email;
            profile.labelChips.Content = user.Chips;
            profile.labelStatus.Content = this.LabelMessageConnected;
            profile.labelTimeWon.Content = user.TimeWon;
            profile.labelLevelString.Content = user.GetLevel;
            string path="LevelImages/Level"+user.UserLevel+".jpg";
            changePicture(profile.imageLevel,path);
            profile.ShowDialog();
        }
        
    }
}
